package view;

import model.Video;
import javafx.embed.swing.JFXPanel;
import javafx.application.Platform;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.List;
import javafx.util.Duration;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class FrontView extends JFrame {
    private final JList<Video> videoList;
    private final DefaultListModel<Video> listModel;
    private final JButton playButton;
    private final JButton stopButton;
    private final JButton nextButton;
    private final JPanel videoPanel;
    private final JPanel controlPanel;
    private JButton pauseButton;       // 新增暂停按钮
    private JSlider progressSlider;  // 进度条
    private JPanel mainVideoContainer;  // 新增主容器
    private MediaPlayer currentPlayer;
    private static final Logger LOGGER = Logger.getLogger(FrontView.class.getName());
    private boolean isPaused = false;  // 播放状态标志
    private boolean userIsDraggingSlider = false; // 防止用户拖动时的冲突
    public FrontView() {
        setTitle("在线视频播放器");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 视频列表
        listModel = new DefaultListModel<>();
        videoList = new JList<>(listModel);
        videoList.setCellRenderer(new VideoListRenderer());
        add(new JScrollPane(videoList), BorderLayout.WEST);

        // 控制按钮面板
        controlPanel = new JPanel();
        playButton = new JButton("播放");
        stopButton = new JButton("停止");
        pauseButton = new JButton("暂停");
        nextButton = new JButton("下一首");

        controlPanel.add(playButton);
        controlPanel.add(stopButton);
        controlPanel.add(pauseButton);  // buttonPanel是已有的按钮容器
        controlPanel.add(nextButton);
        add(controlPanel, BorderLayout.SOUTH);

        mainVideoContainer = new JPanel(new BorderLayout());

        // 视频播放面板
        videoPanel = new JPanel(new BorderLayout());
        add(videoPanel, BorderLayout.CENTER);

        // 初始化进度条（添加在视频面板附近）
        JPanel progressPanel = new JPanel();
        progressSlider = new JSlider(0, 100, 0);
        progressSlider.setPreferredSize(new Dimension(600, 20));
        progressPanel.add(progressSlider);
        progressSlider.addChangeListener(e -> {
            if (userIsDraggingSlider && currentPlayer != null) {
                double fraction = progressSlider.getValue() / 100.0;
                Duration seekTime = currentPlayer.getTotalDuration().multiply(fraction);
                currentPlayer.seek(seekTime);
            }
        });

        // 添加到视频面板
        videoPanel.add(progressSlider, BorderLayout.SOUTH);
        // 在构造函数中添加滑块事件监听
        progressSlider.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                userIsDraggingSlider = true;
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                userIsDraggingSlider = false;
                if (currentPlayer != null) {
                    double fraction = progressSlider.getValue() / 100.0;
                    Duration seekTime = currentPlayer.getTotalDuration().multiply(fraction);
                    currentPlayer.seek(seekTime);
                }
            }
        });

        // 组装组件
        mainVideoContainer.add(videoPanel, BorderLayout.CENTER);
        mainVideoContainer.add(progressPanel, BorderLayout.SOUTH);

        // 添加到主框架
        add(mainVideoContainer, BorderLayout.CENTER);

        // 初始化按钮状态
        updateButtonStates(false);
    }

    public void setVideoList(List<Video> videos) {
        listModel.clear();
        for (Video video : videos) {
            listModel.addElement(video);
        }
        updateButtonStates(false);
        //System.out.println("列表模型当前元素数: " + listModel.size()); // 调试输出
        //System.out.println("列表已更新，显示 " + listModel.size() + " 个视频"); // 调试
    }

    public Video getSelectedVideo() {
        return videoList.getSelectedValue();
    }

    public MediaPlayer getCurrentPlayer() {
        return currentPlayer;
    }

    public void addPlayButtonListener(ActionListener listener) {
        playButton.addActionListener(listener);
    }

    public void addStopButtonListener(ActionListener listener) {
        stopButton.addActionListener(listener);
    }

    public void addNextButtonListener(ActionListener listener) {
        nextButton.addActionListener(listener);
    }
    public void addPauseButtonListener(ActionListener listener) {
        pauseButton.addActionListener(listener);
    }
    private void updateButtonStates(boolean isPlaying) {
        playButton.setEnabled(!isPlaying);
        stopButton.setEnabled(isPlaying);
        nextButton.setEnabled(listModel.size() > 1 && !isPlaying);
    }

    public void playNextVideo() {
        int currentIndex = videoList.getSelectedIndex();
        if (currentIndex < listModel.size() - 1) {
            videoList.setSelectedIndex(currentIndex + 1);
            Video nextVideo = getSelectedVideo();
            if (nextVideo != null) {
                playVideo(nextVideo.getFilePath());
            }
        } else {
            JOptionPane.showMessageDialog(this,
                    "已经是最后一个视频",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public void playVideo(String resourcePath) {
        // 停止并释放之前的播放器
        if (currentPlayer != null) {
            currentPlayer.stop();
            currentPlayer.dispose();
            currentPlayer = null;
        }

        videoPanel.removeAll();

        try {
            final JFXPanel fxPanel = new JFXPanel();
            videoPanel.add(fxPanel, BorderLayout.CENTER);
            videoPanel.revalidate();
            videoPanel.repaint();

            URL videoUrl = getClass().getResource(resourcePath);
            if (videoUrl == null) {
                throw new FileNotFoundException("资源未找到: " + resourcePath);
            }

            Platform.runLater(() -> {
                try {
                    Media media = new Media(videoUrl.toExternalForm());
                    currentPlayer = new MediaPlayer(media);

                    currentPlayer.statusProperty().addListener((obs, oldStatus, newStatus) -> {
                        SwingUtilities.invokeLater(() -> updateButtonStates(newStatus == MediaPlayer.Status.PLAYING));

                        if (newStatus == MediaPlayer.Status.READY) {
                            LOGGER.info("视频准备就绪，时长: " + media.getDuration().toSeconds() + "秒");
                        }
                    });

                    // 添加进度监听器（放在player创建之后）
                    currentPlayer.currentTimeProperty().addListener((obs, oldTime, newTime) -> {
                        if (!userIsDraggingSlider && currentPlayer.getTotalDuration().greaterThan(Duration.ZERO)) {
                            double progress = newTime.toMillis() / currentPlayer.getTotalDuration().toMillis();
                            SwingUtilities.invokeLater(() -> {
                                progressSlider.setValue((int)(progress * 100));
                            });
                        }
                    });

                    currentPlayer.setOnEndOfMedia(() -> {
                        LOGGER.info("视频播放结束");
                        SwingUtilities.invokeLater(() -> {
                            if (videoList.getSelectedIndex() < listModel.size() - 1) {
                                nextButton.setEnabled(true);
                            }
                        });
                    });

                    currentPlayer.setOnError(() -> {
                        LOGGER.severe("播放错误: " + currentPlayer.getError());
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(FrontView.this,
                                    "播放错误: " + currentPlayer.getError().getMessage(),
                                    "错误",
                                    JOptionPane.ERROR_MESSAGE);
                            updateButtonStates(false);
                        });
                    });

                    MediaView view = new MediaView(currentPlayer);
                    view.setPreserveRatio(true);
                    view.setFitWidth(videoPanel.getWidth());
                    view.setFitHeight(videoPanel.getHeight());

                    StackPane root = new StackPane(view);
                    fxPanel.setScene(new Scene(root));

                    currentPlayer.play();
                    updateButtonStates(true);

                } catch (Exception e) {
                    LOGGER.log(Level.SEVERE, "初始化媒体失败", e);
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(FrontView.this,
                                "初始化失败: " + e.getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                        updateButtonStates(false);
                    });
                }
            });
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "加载视频失败", e);
            JOptionPane.showMessageDialog(this,
                    "加载失败: " + e.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            updateButtonStates(false);
        }
    }

    /**
     * 暂停视频播放
     */
    public void pauseVideo() {
        if (currentPlayer != null && currentPlayer.getStatus() == MediaPlayer.Status.PLAYING) {
            currentPlayer.pause();
            isPaused = true;
            pauseButton.setText("继续");  // 按钮文本变为"继续"
        }
    }

    /**
     * 恢复视频播放
     */
    public void resumeVideo() {
        if (currentPlayer != null && isPaused) {
            currentPlayer.play();
            isPaused = false;
            pauseButton.setText("暂停");  // 按钮文本变回"暂停"
        }
    }

    /**
     * 切换暂停/继续状态
     */
    public void togglePause() {
        if (isPaused) {
            resumeVideo();
        } else {
            pauseVideo();
        }
    }

    @Override
    public void dispose() {
        if (currentPlayer != null) {
            currentPlayer.stop();
            //currentPlayer.currentTimeProperty().removeListener();
            currentPlayer.dispose();
        }
        super.dispose();
    }

    private static class VideoListRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                      boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (value instanceof Video) {
                Video video = (Video) value;
                setText(video.getTitle() + " (" + video.getViewCount() + "次播放)");
            }
            return this;
        }
    }
}